package com.yuxl.centent.document.service;

import cn.hutool.core.collection.CollUtil;
import com.yuxl.centent.document.entity.ContentDocument;
import com.yuxl.centent.document.repository.ContentDocumentRepository;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author : yuxl
 * @create 2025/9/8 下午7:58
 */
@Slf4j
@Service
public class ContentDocumentService {
    @Resource
    private ContentDocumentRepository contentDocumentRepository;
    @Resource
    private DatabaseClient postgreSqlDatabaseClient;

    public Flux<ContentDocument> findAll() {
        return contentDocumentRepository.findAll();
    }

    public Mono<ContentDocument> findById(Long id) {
        return contentDocumentRepository.findById(id)
                .defaultIfEmpty(new ContentDocument());
    }

    public Mono<ContentDocument> add(ContentDocument user) {
        user.setCreateTime(LocalDateTime.now())
                .setUpdateTime(LocalDateTime.now());
        return contentDocumentRepository.save(user);
    }

    public Mono<Integer> count(ContentDocument user) {
        return contentDocumentRepository.count(user);
    }


    public Flux<ContentDocument> page(ContentDocument user, int page, int size) {
        long offset = (long) (page - 1) * size;
        return contentDocumentRepository.page(user, size, offset);
    }


    public Flux<ContentDocument> list(ContentDocument user) {
        return contentDocumentRepository.list(user);
    }

    public Mono<ContentDocument> updateById(ContentDocument user) {
        return contentDocumentRepository.updateById(user);
    }

    public Mono<Long> deleteById(Long id) {
        return postgreSqlDatabaseClient.sql(String.format("DELETE FROM content_document WHERE id = %s", id))
                .fetch()
                .rowsUpdated();
    }

    public Mono<Long> deleteByIds(List<Long> ids) {
        return Mono.defer(() -> {
            if (CollUtil.isNotEmpty(ids)) {
                return postgreSqlDatabaseClient.sql(String.format("DELETE FROM content_document WHERE id in (%s)",StringUtils.join(ids, ",")))
                        .fetch()
                        .rowsUpdated();
            }
            return Mono.just(0L);
        });
    }

    public Flux<ContentDocument> pathAll() {
        return contentDocumentRepository.pathAll();
    }
}
